<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item label="网格名称" prop="gridId">
        <el-select v-model="formData.gridId" placeholder="请输入网格名称" @change="handleGridChange" :disabled="formData.gridUserId">
          <el-option v-for="item in gridList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <!-- 先做成人工输入，后续考虑自动生成？ -->
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" :disabled="true">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_AQI_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="填报人" prop="userName">
        <!-- 获取当前登录用户，如果是网格员，回显填报人 -->
        <el-input v-model="formData.userName" placeholder="请输入填报人" :disabled="true"/>
      </el-form-item>
      
      <el-form-item label="细颗粒物（PM2.5）" prop="pm25">
        <el-input v-model="formData.pm25" placeholder="请输入细颗粒物（PM2.5）" @change="handlePm25Change" >
          <template #append>µg/m3</template>
        </el-input>
      </el-form-item>
      <el-form-item label="二氧化硫（SO2）" prop="so2">
        <el-input v-model="formData.so2" placeholder="请输入二氧化硫（SO2）" @change="handleSo2Change" >
          <template #append>µg/m3</template>
        </el-input>
      </el-form-item>
      <el-form-item label="一氧化碳（CO）" prop="co">
        <el-input v-model="formData.co" placeholder="请输入一氧化碳（CO）" @change="handleCoChange">
          <template #append>mg/m3</template>
        </el-input>
      </el-form-item>
      <el-form-item label="反馈信息" prop="description">
        <el-input type="textarea" resize="vertical" :autosize="{ minRows: 2, maxRows: 4 }" v-model="formData.description"  />
      </el-form-item>
      <el-divider />
      <el-form-item label="AQI" prop="aqi">
        <el-input v-model="formData.aqi" placeholder="AQI自动计算" :disabled="true"/>
      </el-form-item>
      <el-form-item label="空气质量指数级别" prop="aqiLevel">
        <el-radio-group v-model="formData.aqiLevel" :disabled="true">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_AQI_LEVEL)"
            :key="String(dict.value)"
            :label="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
        <el-popover
          :width="800"
          placement="top"
          popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
        >
          <template #reference>
            <el-icon><QuestionFilled /></el-icon>
          </template>
          <template #default>
            <div
              class="demo-rich-conent"
              style="display: flex; gap: 16px; flex-direction: column"
            >
              <el-image
                :src="AQIInfoImage"
                style="margin-bottom: 8px"
              />
            </div>
          </template>
        </el-popover>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { QuestionFilled } from '@element-plus/icons-vue'
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { AqiApi, AqiVO } from '@/api/envir/aqi'
import { GridApi, GridVO } from '@/api/envir/grid'
import { useUserStore } from '@/store/modules/user'
import AQIInfoImage from '@/assets/imgs/aqi-level-info.png'

/** AQI 表单 */
defineOptions({ name: 'AqiForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userStore = useUserStore()

const userId = computed(() => userStore.user.id)
const userName = computed(() => userStore.user.nickname ?? 'Admin')

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  gridId: undefined,
  gridName: '',
  userId: userId.value,
  userName: userName.value,
  gridUserId: undefined,
  gridUserName: undefined,
  name: undefined,
  pm25: undefined,
  so2: undefined,
  co: undefined,
  aqiLevel: undefined,
  description: undefined,
  pm25Confirm: undefined,
  so2Confirm: undefined,
  coConfirm: undefined,
  aqiLevelConfirm: undefined,
  descriptionConfirm: undefined,
  aqi: undefined,
  aqiConfirm: undefined,
  status: 0
})
const formRules = reactive({
  gridId: [{ required: true, message: '网格ID不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  // gridUserId: [{ required: true, message: '网格用户ID不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  pm25: [{ required: true, message: '细颗粒物（PM2.5）不能为空', trigger: 'blur' }],
  so2: [{ required: true, message: '二氧化硫（SO2）不能为空', trigger: 'blur' }],
  co: [{ required: true, message: '一氧化碳（CO）不能为空', trigger: 'blur' }],
  // aqiLevel: [{ required: true, message: '空气质量指数级别不能为空', trigger: 'blur' }],
  // description: [{ required: true, message: '反馈信息不能为空', trigger: 'blur' }],
  pm25Confirm: [{ required: true, message: '细颗粒物（PM2.5）-确认值不能为空', trigger: 'blur' }],
  so2Confirm: [{ required: true, message: '二氧化硫（SO2）-确认值不能为空', trigger: 'blur' }],
  coConfirm: [{ required: true, message: '一氧化碳（CO）-确认值不能为空', trigger: 'blur' }],
  // aqiLevelConfirm: [{ required: true, message: '空气质量指数级别-确认值不能为空', trigger: 'blur' }],
  // descriptionConfirm: [{ required: true, message: '反馈信息）-确认值不能为空', trigger: 'blur' }],
  // status: [{ required: true, message: '状态(0-待指派 1-已指派 2-已完成)不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const gridList = ref([] as GridVO[]) // 

const handleGridChange = (gridId: number) => {
  const grid = gridList.value.find(item => item.id === gridId)
  if (grid) {
    formData.value.gridName = grid.name
  }
}

const handlePm25Change = () => {
  formData.value.aqi = undefined
  formData.value.aqiLevel = undefined
  calculateAqi()
}

const handleSo2Change = () => {
  formData.value.aqi = undefined
  formData.value.aqiLevel = undefined
  calculateAqi()
}

const handleCoChange = () => {
  formData.value.aqi = undefined
  formData.value.aqiLevel = undefined
  calculateAqi()
}

const calculateAqi = async() => {
  const pm25 = formData.value.pm25
  const so2 = formData.value.so2
  const co = formData.value.co
  if (pm25 && so2 && co) {
    const data = formData.value as unknown as AqiVO
    const aqi = await AqiApi.calculateAqi(data)
    formData.value.aqi = aqi.aqi
    formData.value.aqiLevel = aqi.aqiLevel
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AqiApi.getAqi(id)
    } finally {
      formLoading.value = false
    }
  }
   // 获得网格的列表
  gridList.value = await GridApi.getSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AqiVO
    if (formType.value === 'create') {
      await AqiApi.createAqi(data)
      message.success(t('common.createSuccess'))
    } else {
      await AqiApi.updateAqi(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    gridId: undefined,
    gridName: '',
    userId: userId.value,
    userName: userName.value,
    gridUserId: undefined,
    gridUserName: undefined,
    name: undefined,
    pm25: undefined,
    so2: undefined,
    co: undefined,
    aqiLevel: undefined,
    description: undefined,
    pm25Confirm: undefined,
    so2Confirm: undefined,
    coConfirm: undefined,
    aqiLevelConfirm: undefined,
    descriptionConfirm: undefined,
    aqi: undefined,
    aqiConfirm: undefined,
    status: 0
  }
  formRef.value?.resetFields()
}
</script>